package com.xuanyuanxinyu.func.gilde;

import android.content.Context;
import android.graphics.Picture;
import android.graphics.drawable.PictureDrawable;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.resource.SimpleResource;
import com.bumptech.glide.load.resource.transcode.ResourceTranscoder;
import com.bumptech.glide.module.AppGlideModule;
import com.caverock.androidsvg.SVG;


import java.io.InputStream;

/**
 * Glide 自定义扩展，可以定义全局配置的缓存大小和图片解码格式
 */
@GlideModule
public class OkhttpGlideModule extends AppGlideModule {

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        super.registerComponents(context, glide, registry);
        OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(ApiManager.getInstance().getApiHttp().getOkHttpClient());
        registry.replace(GlideUrl.class, InputStream.class, factory);
        registry.register(SVG.class, PictureDrawable.class, new SvgDrawableTranscoder())
                .append(InputStream.class, SVG.class, new SvgDecoder());
    }

    public static class SvgDrawableTranscoder implements ResourceTranscoder<SVG, PictureDrawable> {

        private final PictureDrawableUtils mPictureDrawableUtils = new PictureDrawableUtils();

        @Override
        public Resource<PictureDrawable> transcode(Resource<SVG> resource, Options options) {
            SVG svg = resource.get();
            Picture picture = svg.renderToPicture();
            PictureDrawable drawable = mPictureDrawableUtils.pictureDrawableFromPicture(picture);
            return new SimpleResource<>(drawable);
        }
    }
}
